package com.me.permission.autoconfigure;

import com.me.permission.PermissionInterceptor;
import com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author ME
 */
@Configuration
@ConditionalOnBean({SqlSessionFactory.class})
@ConditionalOnProperty(prefix = "me.mybatis.plugin", name = "permission", havingValue = "true", matchIfMissing = true)
public class PermissionHelperAutoConfiguration {

    private static List<SqlSessionFactory> sqlSessionFactoryList;

    @Autowired
    public void setSqlSessionFactoryList(List<SqlSessionFactory> sqlSessionFactoryList) {
        PermissionHelperAutoConfiguration.sqlSessionFactoryList = sqlSessionFactoryList;
    }

    @Configuration
    @AutoConfigureOrder(Integer.MAX_VALUE)
    public static class PermissionAutoConfiguration {

        @PostConstruct
        public void addPageInterceptor() {
            PermissionInterceptor myPlugin = new PermissionInterceptor();
            // 设置参数，比如阈值等，可以在配置文件中配置
            // Properties properties = new Properties();
            // properties.setProperty("time", "1");
            // myPlugin.setProperties(properties);
            for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
                sqlSessionFactory.getConfiguration().addInterceptor(myPlugin);
            }
        }
    }

    @Configuration
    @AutoConfigureOrder(Integer.MAX_VALUE)
    @AutoConfigureAfter(PageHelperAutoConfiguration.class)
    public static class PermissionAfterPageHelperAutoConfiguration {

        @PostConstruct
        public void addPageInterceptor() {
            PermissionInterceptor myPlugin = new PermissionInterceptor();
            // 设置参数，比如阈值等，可以在配置文件中配置
            // Properties properties = new Properties();
            // properties.setProperty("time", "1");
            // myPlugin.setProperties(properties);
            for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
                sqlSessionFactory.getConfiguration().addInterceptor(myPlugin);
            }
        }
    }

}
